package cn.kshost.zqyg.service.pay.service.impl;

import cn.kshost.zqyg.exception.ZhongQiaoException;
import cn.kshost.zqyg.exception.ZqygExceptionHandler;
import cn.kshost.zqyg.model.entity.pay.PaymentInfo;
import cn.kshost.zqyg.model.vo.common.ResultCodeEnum;
import cn.kshost.zqyg.service.pay.mapper.PaymentInfoMapper;
import cn.kshost.zqyg.service.pay.properties.AlipayProperties;
import cn.kshost.zqyg.service.pay.service.AliPayService;
import cn.kshost.zqyg.service.pay.service.PaymentInfoService;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.domain.GoodsDetail;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
  // lombok的注解，对外声明异常
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    @SneakyThrows
    public String submitAlipay(String orderId) {
        //插入订单 并返回返回payment
        PaymentInfo paymentInfo = paymentInfoService.addPaymentInfo(orderId);

        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getServerUrl(),alipayProperties.getAppId(),alipayProperties.getPrivateKey(),"json", "UTF-8", alipayProperties.getAlipayPublicKey(),"RSA2");
        // 构造请求参数以调用接
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        // 设置商户订单号
        model.setOutTradeNo(paymentInfo.getOrderNo());
        // 设置订单总金额
        model.setTotalAmount(String.valueOf(paymentInfo.getAmount()));
//        model.setTotalAmount("0.01");
        // 设置订单标题
        model.setSubject(paymentInfo.getContent());
        // 设置产品码
        model.setProductCode("QUICK_WAP_WAY");
        request.setNotifyUrl(alipayProperties.getNotifyUrl());
        request.setReturnUrl(alipayProperties.getReturnPaymentUrl());
        request.setBizModel(model);
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            return pageRedirectionData;
        } else {
            System.out.println("调用失败");
            throw new ZhongQiaoException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    @SneakyThrows
    public String callbackNotify(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
//公钥验签示例代码
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), "utf-8", "RSA2");
//公钥证书验签示例代码

        // 交易状态
        String trade_status = params.get("trade_status");
//   boolean flag = AlipaySignature.rsaCertCheckV1(params,alipayPublicCertPath,"UTF-8","RSA2");
        if (signVerified) {
            if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
                log.info("验签成功111");
                // TODO 验签成功后
            paymentInfoService.handlePaymentInfo(params,2); //2是支付宝支付
                //按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success
            }
            if (params.get("trade_status").equals("TRADE_SUCCESS")) {
                System.out.println("成功支付");
                System.out.println("======================佛祖保佑 永无bug================================");
                return "success";
            }
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回fail.
            System.err.println("验签失败============================");
        }
        return "fail";
    }


}
